package org.dev.biz_login

import android.app.Application
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import org.dev.`as`.project.common.http.ApiFactory
import org.dev.`as`.project.common.utils.SPUtil
import org.dev.biz_login.api.AccountApi
import org.dev.hi.library.cache.HiStorage
import org.dev.hi.library.executor.HiExecutor
import org.dev.hi.library.restful.HiCallback
import org.dev.hi.library.restful.HiResponse
import org.dev.hi.library.util.AppGlobals
import org.dev.service_login.UserProfile
import java.lang.IllegalStateException

/**
 * Author WenPing
 * CreateTime 2021/5/13.
 * Description:用户登录信息-管理
 */
object AccountManager {

    private var userProfile: UserProfile? = null

    // 修饰 优化多线程操作
    @Volatile
    private var isFeatching = false

    private val loginLiveData = MutableLiveData<Boolean>()

    private var loginForeverObservers = mutableListOf<Observer<Boolean>>()

    private val KEY_USER_PROFILE = "key_user_profile"

    private val profileLiveData = MutableLiveData<UserProfile>()

    private val profileForeverLiveData = mutableListOf<Observer<UserProfile?>>()

    private val KEY_BOARDING_PASS = "boarding_pass"

    private var boardingPass: String? = null

    /**
     * 登录方法
     */
    fun login(
        context: Context? = AppGlobals.get(),
        observer: Observer<Boolean>
    ) {
        if (context is LifecycleOwner) {
            loginLiveData.observe(context, observer)
        } else {
            loginLiveData.observeForever(observer)
            loginForeverObservers.add(observer)
        }

        // 拉起登录
        val intent = Intent(context, LoginActivity::class.java)
        if (context is Application) {
            //跳转新的页面需要添加这个flag FLAG_ACTIVITY_NEW_TASK
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        if (context == null) {
            throw IllegalStateException("context cannot be null")
        }
        context.startActivity(intent)
    }

    /**
     * 登录成功
     * boardingPass 身份标记
     */
    fun loginSuccess(boardingPass: String) {
        SPUtil.putString(KEY_BOARDING_PASS, boardingPass)
        AccountManager.boardingPass = boardingPass

        //发送结果
        loginLiveData.value = true
        //清空所有观察者，避免内存泄漏
        clearLoginForeverObservers()
    }

    private fun clearLoginForeverObservers() {
        for (observer in loginForeverObservers) {
            //遍历 清空
            loginLiveData.removeObserver(observer)
        }
        // 清空 所有观察者
        loginForeverObservers.clear()
    }

    fun getBoardingPass(): String? {
        if (TextUtils.isEmpty(boardingPass)) {
            boardingPass = SPUtil.getString(KEY_BOARDING_PASS)
        }
        return boardingPass
    }

    // 用同步字段修饰该方法
    @Synchronized
    fun getUserProfile(
        lifecycleOwner: LifecycleOwner?,
        observer: Observer<UserProfile?>,
        onlyCache: Boolean // 当 onlyCache时使用缓存数据
    ) {

        if (lifecycleOwner == null) {
            profileLiveData.observeForever(observer)
            profileForeverLiveData.add(observer)
        } else {
            profileLiveData.observe(lifecycleOwner, observer)
        }

        if (userProfile != null && onlyCache) {
            profileLiveData.value = userProfile
            return
        }
        if (isFeatching) return
        isFeatching = true

        ApiFactory.create(AccountApi::class.java)
            .profile()
            .enqueue(object : HiCallback<UserProfile> {
                override fun onSuccess(hiResponse: HiResponse<UserProfile>) {
                    userProfile = hiResponse.data
                    if (hiResponse.code == HiResponse.SUCCESS && userProfile != null) {
                        profileLiveData.value = userProfile
                        // 开启线程，存放用户数据
                        HiExecutor.execute(runnable = Runnable {
                            HiStorage.saveCache(KEY_USER_PROFILE, userProfile)
                            isFeatching = false
                        })
                    } else {
                        //提示，设置liveData的value为空
                        profileLiveData.value = null
                    }
                    clearProfileForeverObservers()
                }

                override fun onFailed(throws: Throwable) {
                    isFeatching = false
                    profileLiveData.value = null
                    clearProfileForeverObservers()
                }
            })
    }

    private fun clearProfileForeverObservers() {
        for (observer in profileForeverLiveData) {
            profileLiveData.removeObserver(observer)
        }
        profileForeverLiveData.clear()
    }

    /**
     * 判断是否登录
     */
    fun isLogin(): Boolean {
        return TextUtils.isEmpty(getBoardingPass())
    }

}